import { createSlice } from '@reduxjs/toolkit'
const shopSlice = createSlice({
    name: 'shop',
    initialState: {
        list: [
            {
                id: 0,
                title: '苹果',
                price: 11
            },
            {
                id: 1,
                title: '鸡蛋',
                price: 6
            },
            {
                id: 2,
                title: '香蕉',
                price: 8
            },
        ],
        cars: [],
    },
    reducers: {
        addOne(state, { payload }) {
            let index = state.cars.findIndex(item => item.id === payload)
            if (index > -1) {
                state.cars[index].num += 1
            } else {
                let item = state.list.find(item => item.id === payload)
                item.num = 1
                state.cars.unshift(item)
            }
        },
        delOne(state, { payload }) {
            let item = state.cars.find(item => item.id === payload)
            if (item.num <= 1) {
                state.cars.splice(item, 1)
            } else {
                item.num -= 1
            }
        }
    }
})
export const { addOne ,delOne} = shopSlice.actions
export default shopSlice.reducer